# 开发者：李奕成
# 开发时间：2024/9/14 14:29
from django.shortcuts import render, redirect, get_object_or_404
from .models import Task
from datetime import datetime
from django.utils import timezone


def todolist(request):
    if request.method == "POST":
        if 'task_id' in request.POST:  # 更新任务的完成状态
            task_id = request.POST.get("task_id")
            task = Task.objects.get(id=task_id)
            task.completed = request.POST.get("completed") is not None  # 更新完成状态
            task.save()
        elif 'delete_task_id' in request.POST:  # 删除任务
            delete_task_id = request.POST.get("delete_task_id")
            task_to_delete = get_object_or_404(Task, id=delete_task_id)
            task_to_delete.delete()  # 删除任务
            return redirect('todolist')  # 重定向
        elif 'title' in request.POST:  # 添加新任务
            title = request.POST.get("title")
            due_date = request.POST.get("due_date")
            if title:
                task = Task(title=title)
                if due_date:
                    task.due_date = datetime.strptime(due_date, "%Y-%m-%dT%H:%M")  # 解析为 datetime
                task.save()  # 保存任务
                return redirect('todolist')  # 添加后重定向

    tasks = Task.objects.all()  # 获取所有任务
    current_time = timezone.now()  # 使用时区感知的当前时间
    for task in tasks:
        if task.due_date:  # 确保 due_date 不为空
            remaining_time = task.due_date - current_time  # 计算剩余时间
            task.remaining_time_days = remaining_time.days
            task.remaining_time_hours = remaining_time.seconds // 3600
            task.remaining_time_minutes = (remaining_time.seconds // 60) % 60
        else:
            task.remaining_time_days = None
            task.remaining_time_hours = None
            task.remaining_time_minutes = None

    return render(request, 'toDoList.html', {"tasks": tasks})  # 渲染模板


